package com.itxiaofeng.spzx.manager.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.itxiaofeng.spzx.common.exception.GuiguException;
import com.itxiaofeng.spzx.model.dto.system.LoginDto;
import com.itxiaofeng.spzx.model.entity.system.SysUser;
import com.itxiaofeng.spzx.model.vo.common.ResultCodeEnum;
import com.itxiaofeng.spzx.model.vo.system.LoginVo;
import com.itxiaofeng.spzx.manager.mapper.SysUserMapper;
import com.itxiaofeng.spzx.manager.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;


import java.security.Key;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public LoginVo login(LoginDto loginDto) {

        // 获取输入的验证码和存储到redis的key名称
        String captcha = loginDto.getCaptcha();
        String codeKey = loginDto.getCodeKey();
        // 根据key查redis里面的key
        String redisCode = redisTemplate.opsForValue().get("user:validate" + codeKey);
        // 比较输入的验证码和redis存储验证码是否一致
        if (StrUtil.isEmpty(redisCode) || !StrUtil.equalsIgnoreCase(redisCode,captcha)) {
            throw new GuiguException(ResultCodeEnum.VALIDATECODE_ERROR);
        }

        // 如果一致，删除redis里面的验证码
        redisTemplate.delete("user:validate" + codeKey);



        // 获取提交用户名，logindto获取到
        String userName = loginDto.getUserName();
        // 更加用户名查询数据库表sys_user表
        SysUser sysUser = sysUserMapper.selectByUserName(userName);
        // 如果根据用户名查不到对应信息，用户不存在，返回错误信息
        if (sysUser == null) {
            throw new GuiguException(ResultCodeEnum.LOGIN_ERROR);
        }
        // 如果根据用户名查询到用户信息，用户存在
        // 获取输入的密码进行加密，在比较数据库密码md5
        String password = sysUser.getPassword();
        String input_password = DigestUtils.md5DigestAsHex(loginDto.getPassword().getBytes());
        // 比较
        if (!input_password.equals(password)) {
            throw new GuiguException(ResultCodeEnum.LOGIN_ERROR);
        }
        // 如果密码一致，登录成功，生成唯一标识Token
        String token = UUID.randomUUID().toString().replaceAll("-","");

        // 把登录成功的用户信息放到redis里面
        redisTemplate.opsForValue().set("user:login=" + token,
                JSON.toJSONString(sysUser),
                7,
                TimeUnit.DAYS);
        // 返回loginvo对象
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);

        return loginVo;
    }

    @Override
    public SysUser getUserInfo(String token) {
        String userJson = redisTemplate.opsForValue().get("user:login=" + token);
        return JSON.parseObject(userJson , SysUser.class) ;
    }

    @Override
    public void logout(String token) {
        redisTemplate.delete("user:login=" + token) ;
    }
}
